<template>
  <div class="category-form-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>{{ isEdit ? "编辑分类" : "新增分类" }}</h2>
        </div>
        <div class="header-right">
          <el-button @click="handleCancel">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <el-form
        ref="categoryFormRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <!-- 中英文选择 -->
        <el-form-item label="中英文:" prop="language">
          <el-select
            v-model="formData.language"
            placeholder="请选择语言版本"
            style="width: 200px"
          >
            <el-option label="中文" value="zh-CN" />
            <el-option label="英文" value="en" />
          </el-select>
        </el-form-item>

        <!-- 分类名称 -->
        <el-form-item label="分类名称:" prop="categoryName">
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入分类名称"
            style="width: 300px"
          />
        </el-form-item>

        <!-- 分类层级 -->
        <el-form-item label="分类层级:" prop="level">
          <el-input-number
            v-model="formData.level"
            :min="1"
            :max="10"
            :precision="0"
            placeholder="请输入分类层级"
            style="width: 200px"
          />
        </el-form-item>

        <!-- 分类描述 -->
        <el-form-item label="分类描述:" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
            style="width: 500px"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <div class="form-actions">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import {
  createProductCategory,
  updateProductCategory,
  getProductCategoryDetail,
} from "@/api/product/category";

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 表单引用
const categoryFormRef = ref();

// 表单数据
const formData = reactive({
  language: "",
  categoryName: "",
  description: "",
  level: 1,
});

// 表单验证规则
const formRules = {
  language: [{ required: true, message: "请选择语言版本", trigger: "change" }],
  categoryName: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 1, max: 50, message: "分类名称长度在1-50个字符", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "描述长度不能超过200个字符", trigger: "blur" },
  ],
  level: [
    { required: true, message: "请输入分类层级", trigger: "blur" },
    {
      type: "number",
      min: 1,
      max: 10,
      message: "层级必须在1-10之间",
      trigger: "blur",
    },
  ],
};

// 表单提交
const handleSubmit = async () => {
  try {
    await categoryFormRef.value?.validate();

    const submitData = { ...formData };
    const res = isEdit.value
      ? await updateProductCategory({ ...submitData, id })
      : await createProductCategory(submitData);

    const responseData = res as any;
    if (responseData?.code === 200) {
      ElMessage.success(`${isEdit.value ? "更新" : "保存"}成功`);
      router.push("/product-category-list");
    } else {
      ElMessage.error(
        responseData?.msg || `${isEdit.value ? "更新" : "保存"}失败`
      );
    }
  } catch (error) {
    if (error !== false) {
      console.error("提交失败:", error);
      ElMessage.error("操作失败，请稍后重试");
    }
  }
};

// 取消操作
const handleCancel = () => router.back();

// 加载分类数据
const loadCategoryData = async (categoryId: string) => {
  try {
    const res = await getProductCategoryDetail(categoryId);
    const responseData = res as any;

    if (responseData?.code === 200 && responseData.data) {
      Object.assign(formData, {
        language: responseData.data.language || "",
        categoryName: responseData.data.categoryName || "",
        description: responseData.data.description || "",
        level: responseData.data.level || 1,
      });
    } else {
      ElMessage.error("获取分类详情失败");
    }
  } catch (error) {
    console.error("加载分类数据失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 页面初始化
onMounted(() => {
  if (isEdit.value) {
    // 编辑模式：加载现有数据
    loadCategoryData(id);
  }
});
</script>

<style scoped>
.category-form-container {
  padding: 20px;
  min-height: 100vh;
}

.page-header {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
}

.header-left h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .category-form-container {
    padding: 10px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .form-content {
    padding: 20px;
  }

  .form-actions {
    justify-content: center;
  }
}
</style>
